'use client';

import { useState, useEffect, KeyboardEvent, useCallback } from 'react';
import { useAuth } from '@/hooks/use-auth';
import { useRouter } from 'next/navigation';
import { toast } from '@/components/ui/use-toast';
import SocketProviderWrapper from '@/components/socket-provider-wrapper';
import { useSocket } from '@/components/socket-io-provider';
import { safeEventHandler } from '@/lib/socket-mock';
import CollaborativeEditor from '@/components/collaborative-editor';
import CollaborationStatus from '@/components/collaboration-status';

// 定义项目数据类型
interface ProjectData {
  id: string;
  name: string;
  ownerId: string;
  members?: {
    userId: string;
    role: string;
  }[];
}

// 编辑器内容组件 - 客户端组件
export default function EditorContent({ projectId }: { projectId: string }) {
  const { user } = useAuth();
  const router = useRouter();
  
  const [content, setContent] = useState('在此处编辑项目内容...');
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [projectData, setProjectData] = useState<ProjectData | null>(null);
  const [lastSaved, setLastSaved] = useState<string | null>(null);

  // 加载项目内容
  useEffect(() => {
    const loadProjectContent = async () => {
      try {
        setIsLoading(true);
        console.log('加载项目内容...', { projectId });

        // 获取项目基本信息
        try {
          const projectResponse = await fetch(`/api/projects/${projectId}`);
          if (!projectResponse.ok) {
            console.error('获取项目信息失败:', projectResponse.status);
            // 不中断流程，允许本地编辑模式
          } else {
            const project = await projectResponse.json();
            console.log('项目数据获取成功:', project);
            setProjectData(project.data || project); // 兼容不同API返回格式
          }
        } catch (projectError) {
          console.error('获取项目信息请求异常:', projectError);
          // 不中断流程，允许本地编辑模式
        }

        // 尝试从本地存储加载内容
        const localData = localStorage.getItem(`project-${projectId}`);
        if (localData) {
          try {
            const parsed = JSON.parse(localData);
            setContent(parsed.content || '');
            console.log('从本地存储加载内容成功');
          } catch (e) {
            console.error('解析本地存储数据失败', e);
          }
        }

        // 获取项目内容
        try {
          const contentResponse = await fetch(`/api/projects/${projectId}/content`);
          if (contentResponse.ok) {
            const contentData = await contentResponse.json();
            if (contentData.success && contentData.data?.content) {
              setContent(contentData.data.content);
              setLastSaved(contentData.data.updatedAt);
              console.log('成功从API加载内容');
            }
          } else {
            console.warn('获取项目内容失败，使用本地内容', contentResponse.status);
            toast({
              title: '从服务器获取内容失败',
              description: '正在使用本地存储的内容',
              duration: 3000,
            });
          }
        } catch (err) {
          console.error('API获取内容失败，使用本地内容', err);
          toast({
            title: '连接服务器失败',
            description: '正在离线模式工作，内容将保存在本地',
            duration: 3000,
          });
        }

      } catch (error) {
        console.error('加载项目失败:', error);
        toast({
          title: '加载失败',
          description: '无法加载项目内容，请刷新页面重试',
          variant: 'destructive',
        });
      } finally {
        setIsLoading(false);
      }
    };

    if (user && projectId) {
      loadProjectContent();
    } else if (projectId) {
      // 如果没有用户但有项目ID，尝试从本地存储加载
      const localData = localStorage.getItem(`project-${projectId}`);
      if (localData) {
        try {
          const parsed = JSON.parse(localData);
          setContent(parsed.content || '');
          setIsLoading(false);
        } catch (e) {
          console.error('解析本地存储数据失败', e);
          setIsLoading(false);
        }
      } else {
        setIsLoading(false);
      }
    }
  }, [user, projectId]);

  // 保存到本地
  const saveToLocal = () => {
    try {
      const saveTime = new Date().toISOString();
      localStorage.setItem(`project-${projectId}`, JSON.stringify({
        content,
        lastSaved: saveTime
      }));
      return true;
    } catch (error) {
      console.error('保存到本地失败', error);
      return false;
    }
  };

  // 保存到数据库
  const handleSave = async () => {
    // 先保存到本地
    const localSaved = saveToLocal();
    
    if (localSaved) {
      toast({
        title: '本地保存成功',
        description: '内容已保存到浏览器本地存储',
        duration: 2000,
      });
    }
    
    if (!user) {
      toast({
        title: '未登录',
        description: '内容已保存到本地，登录后可保存到云端',
        variant: 'default',
      });
      return;
    }

    if (!content.trim()) {
      toast({
        title: '内容为空',
        description: '请输入一些内容后再保存',
        variant: 'destructive',
      });
      return;
    }

    try {
      setIsSaving(true);
      console.log('开始保存项目内容到数据库...', { projectId, contentLength: content.length });

      const response = await fetch(`/api/projects/${projectId}/content`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          content: content.trim(),
        }),
      });

      console.log('保存响应状态:', response.status);
      
      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.message || `保存到服务器失败: ${response.status}`);
      }
      
      const result = await response.json();
      console.log('保存成功:', result);
      
      if (result.success) {
        setLastSaved(result.data.updatedAt);
        toast({
          title: '保存成功',
          description: '项目内容已成功保存到数据库',
          duration: 3000,
        });
      } else {
        throw new Error(result.message || '保存失败');
      }

    } catch (error: any) {
      console.error('保存项目内容到数据库失败:', error);
      toast({
        title: '保存到服务器失败',
        description: '内容已保存在本地，但无法同步到服务器',
        variant: 'destructive',
        duration: 5000,
      });
    } finally {
      setIsSaving(false);
    }
  };
  
  // 添加键盘快捷键支持
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement> | KeyboardEvent) => {
      if (e.ctrlKey && e.key === 's') {
        e.preventDefault();
        handleSave();
      }
    };

    document.addEventListener('keydown', handleKeyDown as any);
    return () => {
      document.removeEventListener('keydown', handleKeyDown as any);
    };
  }, [content, user, projectId]);

  // 检查用户权限
  // 如果没有获取到项目数据或用户数据，允许本地编辑模式
  const canEdit = !projectData || !user || (
    projectData.ownerId === user.id || 
    projectData.members?.some(member => 
      member.userId === user.id && ['ADMIN', 'EDITOR'].includes(member.role)
    )
  );
  
  // 记录当前状态用于调试
  useEffect(() => {
    console.log('编辑器组件状态:', {
      isLoading,
      hasUser: !!user,
      userId: user?.id,
      hasProjectData: !!projectData,
      projectOwnerId: projectData?.ownerId,
      projectId,
      canEdit,
      projectMembersCount: projectData?.members?.length || 0,
      isOwner: user && projectData ? user.id === projectData.ownerId : false,
    });
  }, [isLoading, user, projectData, canEdit, projectId]);

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500 mx-auto mb-4"></div>
          <p className="text-gray-600">加载项目内容中...</p>
        </div>
      </div>
    );
  }

  if (!user) {
    return (
      <div className="min-h-screen bg-gray-50 p-6">
        <div className="max-w-4xl mx-auto bg-white rounded-lg shadow-sm p-6">
          <div className="flex justify-between items-center mb-6">
            <div>
              <h1 className="text-2xl font-bold text-gray-900">本地编辑模式</h1>
              <p className="text-sm text-gray-500 mt-1">
                您当前未登录，内容将只保存在本地设备上
              </p>
            </div>
            <div className="flex gap-2">
              <button
                onClick={() => router.push('/auth/signin')}
                className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600"
              >
                去登录
              </button>
            </div>
          </div>
          
          <div className="bg-white rounded-lg border border-gray-200">
            <div className="p-4">
              <SocketProviderWrapper projectId={projectId}>
                <CollaborativeEditor
                  projectId={projectId}
                  value={content}
                  onChange={setContent}
                  placeholder="在此处编辑项目内容..."
                  className="w-full min-h-[400px] p-4 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500 resize-none font-mono text-sm"
                />
              </SocketProviderWrapper>
            </div>
            
            <div className="border-t border-gray-100 p-4 bg-gray-50 rounded-b-lg flex justify-between items-center">
              <span className="text-sm text-gray-500">字符数: {content.length}</span>
              <button
                onClick={() => saveToLocal()}
                className="px-4 py-2 bg-green-500 text-white rounded-md hover:bg-green-600"
              >
                保存到本地
              </button>
            </div>
          </div>
          
          <div className="mt-4 bg-yellow-50 border border-yellow-200 rounded p-4">
            <p className="text-sm text-yellow-700">
              <strong>注意:</strong> 本地模式下，内容只会保存在当前设备的浏览器中。如需同步到云端，请登录后使用。
            </p>
          </div>
        </div>
      </div>
    );
  }

  if (false) { 
    // 暂时禁用权限检查，强制允许编辑
    // 以后恢复正常逻辑: if (!canEdit && user && projectData)
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <p className="text-gray-600 mb-4">您没有权限编辑此项目</p>
          <button
            onClick={() => router.push(`/project/${projectId}`)}
            className="px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600"
          >
            返回项目
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-4xl mx-auto p-6">
        {/* 头部信息 */}
        <div className="bg-white rounded-lg shadow-sm p-6 mb-6">
          <div className="flex justify-between items-start mb-4">
            <div>
              <h1 className="text-2xl font-bold text-gray-900">项目编辑器</h1>
              <p className="text-sm text-gray-500 mt-1">
                项目: {projectData?.name || projectId}
              </p>
              {lastSaved && (
                <p className="text-xs text-gray-400 mt-1">
                  上次保存: {new Date(lastSaved).toLocaleString('zh-CN')}
                </p>
              )}
            </div>
            
            <div className="flex gap-2">
              <button
                onClick={() => router.push(`/project/${projectId}`)}
                className="px-4 py-2 text-gray-600 border border-gray-300 rounded-md hover:bg-gray-50 transition-colors"
              >
                返回项目
              </button>
              
              <button
                onClick={handleSave}
                disabled={isSaving || !content.trim()}
                className="px-6 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors flex items-center gap-2"
              >
                {isSaving ? (
                  <>
                    <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                    保存中...
                  </>
                ) : (
                  <>
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3-3m0 0l-3 3m3-3v12" />
                    </svg>
                    保存
                  </>
                )}
              </button>
            </div>
          </div>
        </div>

        {/* 编辑器区域 */}
        <div className="bg-white rounded-lg shadow-sm">
          <div className="border-b border-gray-200 px-6 py-3">
            <h2 className="text-lg font-medium text-gray-900">项目内容</h2>
          </div>
          
          <div className="p-6">
            <SocketProviderWrapper projectId={projectId}>
              <CollaborativeEditor
                projectId={projectId}
                value={content}
                onChange={setContent}
                placeholder="在此处编辑项目内容..."
                className="w-full min-h-[500px] p-4 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500 resize-none font-mono text-sm leading-relaxed"
                style={{ 
                  fontFamily: 'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'
                }}
              />
            </SocketProviderWrapper>
          </div>
          
          <div className="border-t border-gray-200 px-6 py-3 bg-gray-50 rounded-b-lg">
            <div className="flex justify-between items-center text-sm text-gray-500">
              <div className="flex items-center space-x-4">
                <span>字符数: {content.length}</span>
                <SocketProviderWrapper projectId={projectId}>
                  <CollaborationStatus projectId={projectId} />
                </SocketProviderWrapper>
              </div>
              <span>
                {isSaving ? '正在保存...' : lastSaved ? `已保存 (${new Date(lastSaved).toLocaleString('zh-CN')})` : '未保存'}
              </span>
            </div>
          </div>
        </div>

        {/* 快捷键提示 */}
        <div className="mt-6 bg-blue-50 border border-blue-200 rounded-lg p-4">
          <h3 className="text-sm font-medium text-blue-900 mb-2">快捷键提示</h3>
          <div className="text-sm text-blue-700 space-y-1">
            <p><kbd className="px-2 py-1 bg-blue-100 rounded text-xs">Ctrl + S</kbd> 保存内容</p>
            <p><kbd className="px-2 py-1 bg-blue-100 rounded text-xs">Ctrl + Z</kbd> 撤销</p>
            <p><kbd className="px-2 py-1 bg-blue-100 rounded text-xs">Ctrl + Y</kbd> 重做</p>
          </div>
        </div>
      </div>
    </div>
  );
} 